package ru.compft.common.data;

import ru.compft.common.data.meta.PermissionsTableMeta;
import ru.compft.common.data.meta.RoleToPermissionTableMeta;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * User: ASUS
 * Date: 01.06.12
 * Time: 0:10
 * Класс представляющий объект "Права доступа"
 */
@Entity
@Table(name = PermissionsTableMeta.TABLE_NAME)
public class AppPermission implements Serializable {
    private static final long serialVersionUID = 3807253423547257032L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = PermissionsTableMeta.ID, unique = true, nullable = false)
    private Long id;

    @Column(name = PermissionsTableMeta.CODE, unique = true, nullable = false)
    private String code;

    @Column(name = PermissionsTableMeta.NAME)
    private String name;

    @Column(name = PermissionsTableMeta.DESCRIPTION)
    private String description;

    @ManyToMany(
            targetEntity = AppRole.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE},
            fetch = FetchType.EAGER
    )
    @JoinTable(
            name = RoleToPermissionTableMeta.TABLE_NAME,
            joinColumns = @JoinColumn(name = RoleToPermissionTableMeta.PERMISSION_ID),
            inverseJoinColumns = @JoinColumn(name = RoleToPermissionTableMeta.ROLE_ID)
    )
    public Set<AppRole> roles; // роли пользователя

    public AppPermission() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<AppRole> getRoles() {
        return roles;
    }

    public void setRoles(Set<AppRole> roles) {
        this.roles = roles;
    }

    public void addRole(AppRole appRole) {
        if (appRole != null) {
            if (getRoles() == null)
                setRoles(new HashSet<AppRole>());

            getRoles().add(appRole);
        }
    }
}
